package com.lipengcheng.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lipengcheng.item.mapper.ItemMapper;
import com.lipengcheng.item.pojo.Item;
import com.lipengcheng.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.HashMap;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 商品下架上架
     *
     * @param id
     * @param status
     */
    @Transactional
    @Override
    public void updateStatus(Long id, Integer status) {
        //创建商品对象
        Item item = new Item();
        item.setStatus(status);
        item.setId(id);
        itemMapper.updateById(item);
        //根据上下架判断routingkey
        String routingKey = status == 1 ? "item.up" : "item.down";
        //发送消息
        rabbitTemplate.convertAndSend("item.topic", routingKey, id);
    }

    /**
     * 修改商品
     *
     * @param item
     */
    @Override
    public void updateById1(Item item) {
        //获取当前时间并转为Date格式
        Date date = Date.from(LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)));
        item.setUpdateTime(date);
        itemMapper.updateById(item);
    }

    /**
     * 根据id删除菜品
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        itemMapper.deleteById(id);
    }

    /**
     * 扣减库存
     *
     * @param itemId
     * @param num
     */
    @Transactional
    @Override
    public void reduceStock(Long itemId, Integer num) {
        //根据商品id查询对应信息
        try{
        Item item = itemMapper.selectById(itemId);
                int number = item.getStock() - num;
                item.setStock(number);
                itemMapper.updateById(item);}
        catch (Exception e){
        throw new RuntimeException();
        }

    }
}
